package demo12.gumballRemote;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/*
 * RMI的开发步骤

先创建远程接口及声明远程方法，注意这是实现双方通讯的接口，需要继承Remote
开发一个类来实现远程接口及远程方法，值得注意的是实现类需要继承UnicastRemoteObject
通过javac命令编译文件，通过java -server 命令注册服务，启动远程对象
最后客户端查找远程对象，并调用远程方法
 * 
 * UnicastRemoteObject类
 * 用于导出带 JRMP 的远程对象和获得与该远程对象通信的 stub。*/
public class GumballMachine extends UnicastRemoteObject implements GumballMachineRemote{
	
		private static final long serialVersionUID = 2L;
		State soldOutState;
		State noQuarterState;
		State hasQuarterState;
		State soldState;
		State winnerState;
	 
		State state = soldOutState;
		int count = 0;
	 	String location;

		public GumballMachine(String location, int numberGumballs) throws RemoteException {
			soldOutState = new SoldOutState(this);
			noQuarterState = new NoQuarterState(this);
			hasQuarterState = new HasQuarterState(this);
			soldState = new SoldState(this);
			winnerState = new WinnerState(this);

			this.count = numberGumballs;
	 		if (numberGumballs > 0) {
				state = noQuarterState;
			} 
			this.location = location;
		}
	 
	 
		public void insertQuarter() {
			state.insertQuarter();
		}
	 
		public void ejectQuarter() {
			state.ejectQuarter();
		}
	 
		public void turnCrank() {
			state.turnCrank();
			state.dispense();
		}

		void setState(State state) {
			this.state = state;
		}
	 
		void releaseBall() {
			System.out.println("一个口香糖来轧出槽...");
			if (count != 0) {
				count = count - 1;
			}
		}

		public void refill(int count) {
			this.count = count;
			state = noQuarterState;
		}
	 
		public int getCount() {
			return count;
		}
	 
	    public State getState() {
	        return state;
	    }
	 
	    public String getLocation() {
	        return location;
	    }
	  
	    public State getSoldOutState() {
	        return soldOutState;
	    }

	    public State getNoQuarterState() {
	        return noQuarterState;
	    }

	    public State getHasQuarterState() {
	        return hasQuarterState;
	    }

	    public State getSoldState() {
	        return soldState;
	    }

	    public State getWinnerState() {
	        return winnerState;
	    }
	 
		@Override
		public String toString() {
			StringBuffer result = new StringBuffer();
			result.append("\njava站口香糖模型机器\n");
			result.append("\n库存: " + count + " 糖果");
			result.append("\n");
			result.append("机器状态 是 " + state + "\n");
			result.append("机器位置在"+location+"\n");
			return result.toString();
		}
}
